package org.ne.banksys.controller;

import com.opencsv.CSVWriter;
import jakarta.servlet.http.HttpServletResponse;
import org.ne.banksys.common.Result;
import org.ne.banksys.entity.Card;
import org.ne.banksys.entity.Trade;
import org.ne.banksys.entity.User;
import org.ne.banksys.service.CardService;
import org.ne.banksys.service.DepositService;
import org.ne.banksys.service.TradeService;
import org.ne.banksys.service.UserService;
import org.ne.banksys.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wey
 * @date 2025/6/19 上午9:40 06
 **/


@RestController
@RequestMapping("/download")
public class UploadController {

    @Autowired
    private UserService userService;

    @Autowired
    private CardService cardService;

    @Autowired
    private TradeService tradeService;

    @Autowired
    private DepositService depositService;

    @GetMapping("/allCards")
    public void exportCardsToCsv(HttpServletResponse response) throws IOException {
        // 1. 获取数据（排除password字段）
        Map<String, Object> info = ThreadLocalUtils.get();
        Long id = Long.parseLong(info.get("customerId").toString());
        List<Card> Cards = cardService.selectCardByCustomerId(id);
        // 2. 设置响应头（解决中文乱码问题）
        response.setContentType("text/csv; charset=UTF-8");
        String fileName = "银行卡列表.csv";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + encodedFileName + "\"");

        // 3. 使用OpenCSV写入响应流
        try (CSVWriter csvWriter = new CSVWriter(
                new OutputStreamWriter(response.getOutputStream(), "GBK"))) {

            // 表头保持不变
            csvWriter.writeNext(new String[]{"银行卡号", "客户姓名", "存款类型", "币种", "开户日期", "存款", "挂失"});

            for (Card card : Cards) {
                String[] row = {
                    card.getCardId() != null ? "\t" + card.getCardId() : "",
                    userService.findUserById( card.getCustomerId()).getCustomerName(),
                    depositService.getSavingName(card.getSavingId()),
                    card.getCurId(),
                    "\t"+card.getOpenDate().toString(),
                    card.getBalance().toString(),
                    card.getIsReportLoss()
                };
                csvWriter.writeNext(row);
            }
        }
    }

    @GetMapping("/allTrades")
    public void exportTradesToCsv(HttpServletResponse response) throws IOException {


        List<Trade> trades = tradeService.getAll();
        Map<String ,Object> info = ThreadLocalUtils.get();
        Long id = Long.parseLong(info.get("customerId").toString());
        List<Card> myCards = cardService.selectCardByCustomerId(id);
        List<Trade> myTrades = new ArrayList<>();
        for (Card card : myCards) {

            for (Trade trade : trades) {
                if (trade.getCardId().equals(card.getCardId())) {
                    myTrades.add(trade);
                }
            }

        }



        // 2. 设置响应头（解决中文乱码问题）
        response.setContentType("text/csv; charset=UTF-8");
        String fileName = "交易记录列表.csv";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + encodedFileName + "\"");

        // 3. 使用OpenCSV写入响应流
        try (CSVWriter csvWriter = new CSVWriter(
                new OutputStreamWriter(response.getOutputStream(), "GBK"))) {

            // 表头保持不变
            csvWriter.writeNext(new String[]{"交易ID", "交易日期", "交易类型", "交易银行卡", "交易金额", "备注"});

            for (Trade trade : myTrades) {
                String[] row = {
                    trade.getTradeId() != null ? "\t" + trade.getTradeId() : "",
                    "\t"+trade.getTradeDate().toString(),
                    trade.getTradeType(),
                    "\t" + trade.getCardId(),
                    trade.getTradeMoney().toString(),
                    trade.getRemark()
                };
                csvWriter.writeNext(row);
            }
        }
    }

}
